package com.wm.springcloud.service.impl;

import com.wm.springcloud.service.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName:MyLB
 * @Description: 自定义轮训器实现
 * @Author:Deamer
 * @Date:2021/11/14 10:02
 **/
@Component// 需要跟启动类同包或在其子包下
public class MyLB implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);



    // 负载均衡算法：rest接口第几次请求 % 服务器集群的总数量 = 实际调用服务器位置下标，每次服务器重启后rest接口
    // 计数从1开始
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }

    public final int getAndIncrement() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("**********第几次的访问次数，次数next:" + next);
        return next;
    }
}
